package top.codef.config;

import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.gson.GsonBuilderCustomizer;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import top.codef.gsonsupport.LocalDateTimeGsonAdapter;
import top.codef.gsonsupport.MoneyGsonAdapterFactory;
import top.codef.money.interfaces.MercuryMonetaryAmountFormat;
import top.codef.properties.MercuryGsonProperties;

@Configuration
@ConditionalOnClass(Gson.class)
@EnableConfigurationProperties(MercuryGsonProperties.class)
public class MoneyGsonAutoConfig implements GsonBuilderCustomizer {

	@Autowired
	private MercuryMonetaryAmountFormat mercuryMonetaryAmountFormat;

	@Autowired
	private MercuryGsonProperties mercuryGsonProperties;

	@Override
	public void customize(GsonBuilder gsonBuilder) {
		gsonBuilder.registerTypeAdapterFactory(moneyGsonAdapterFactory()).registerTypeAdapter(
				TypeToken.get(LocalDateTime.class).getType(), new LocalDateTimeGsonAdapter(mercuryGsonProperties));
	}

	@Bean
	public MoneyGsonAdapterFactory moneyGsonAdapterFactory() {
		MoneyGsonAdapterFactory moneyGsonAdapterFactory = new MoneyGsonAdapterFactory(mercuryMonetaryAmountFormat);
		return moneyGsonAdapterFactory;
	}
}
